package com.gateway.video.rtsp.server.handler.support;

import com.gateway.video.rtsp.server.VideoServerConstants;
import com.gateway.video.rtsp.server.util.ApplicationContextUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.rtsp.RtspVersions;
import io.netty.util.concurrent.Promise;
import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.kohsuke.MetaInfServices;
import org.springframework.context.ApplicationContext;

import java.time.LocalDateTime;

@Slf4j
@MetaInfServices(RtspRequest.class)
public class PlayRtspRequest extends AbstractRtspRequest{
    private static final ApplicationContext APPLICATION_CONTEXT = ApplicationContextUtil.getApplicationContext();

    @Override
    protected void doHanlder(ChannelHandlerContext ctx, HttpRequest request, Promise promise) {
        var response = new DefaultFullHttpResponse(RtspVersions.RTSP_1_0, HttpResponseStatus.OK);
        response.headers().set(HttpHeaderNames.SERVER, VideoServerConstants.VIDEO_VERSION);
        response.headers().set(HttpHeaderNames.DATE, LocalDateTime.now());
        response.headers().set("RTP-Info", "url=rtsp://192.168.45.1:12006/trackID=0;seq=49470;rtptime=3158879198");
        response.headers().set(HttpHeaderNames.RANGE, "npt=15.414000-");
        response.headers().set(VideoServerConstants.SESSION, request.headers().get(VideoServerConstants.SESSION));
        response.headers().set(HttpHeaderNames.CONTENT_LENGTH, 0);
        response.headers().set(HttpHeaderNames.CACHE_CONTROL, "no-cache");
        response.headers().set(VideoServerConstants.CSEQ, request.headers().get(VideoServerConstants.CSEQ));

        ctx.writeAndFlush(response, ctx.newPromise().addListener(future -> {
            if(future.isSuccess()) {
                promise.setSuccess(response);
            }else {
                promise.setFailure(future.cause());
            }
        }));
    }

    @Override
    public boolean isSupport(HttpRequest request) {
        return request.method().name().equals(RtspHttpMethod.PLAY.name());
    }
}
